<template>
  <div class="auth-test">
    <el-card>
      <template #header>
        <h3>认证系统测试</h3>
      </template>
      
      <div class="test-section">
        <h4>当前状态</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="登录状态">
            <el-tag :type="isLoggedIn ? 'success' : 'danger'">
              {{ isLoggedIn ? '已登录' : '未登录' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户信息">
            {{ user ? user.username : '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="Token">
            {{ token ? '存在' : '不存在' }}
          </el-descriptions-item>
          <el-descriptions-item label="加载状态">
            <el-tag :type="isLoading ? 'warning' : 'info'">
              {{ isLoading ? '加载中' : '空闲' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="test-section">
        <h4>功能测试</h4>
        <el-space wrap>
          <el-button @click="testRequireAuth" type="primary">
            测试要求登录
          </el-button>
          <el-button @click="testWithAuth" type="success">
            测试安全操作
          </el-button>
          <el-button @click="testValidateAuth" type="warning">
            测试Token验证
          </el-button>
          <el-button @click="testLogout" type="danger" v-if="isLoggedIn">
            测试退出登录
          </el-button>
        </el-space>
      </div>
      
      <div class="test-section">
        <h4>测试结果</h4>
        <el-scrollbar height="200px">
          <div class="test-logs">
            <div 
              v-for="(log, index) in testLogs" 
              :key="index"
              class="log-item"
              :class="log.type"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </el-scrollbar>
        <el-button @click="clearLogs" size="small" style="margin-top: 10px;">
          清除日志
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAuth } from '@/composables/useAuth'
import { useAuthStore } from '@/stores/authStore'
import { ElMessage } from 'element-plus'

const { 
  isLoggedIn, 
  user, 
  isLoading,
  requireAuth, 
  withAuth, 
  validateAuth, 
  logout 
} = useAuth()

const authStore = useAuthStore()
const token = computed(() => authStore.token)

const testLogs = ref([])

// 添加日志
const addLog = (message, type = 'info') => {
  testLogs.value.push({
    time: new Date().toLocaleTimeString(),
    message,
    type
  })
}

// 清除日志
const clearLogs = () => {
  testLogs.value = []
}

// 测试要求登录
const testRequireAuth = () => {
  addLog('开始测试要求登录功能...')
  
  const result = requireAuth('测试：此功能需要登录')
  
  if (result) {
    addLog('✅ 用户已登录，可以继续操作', 'success')
  } else {
    addLog('❌ 用户未登录，已跳转到登录页', 'warning')
  }
}

// 测试安全操作
const testWithAuth = async () => {
  addLog('开始测试安全操作...')
  
  try {
    const result = await withAuth(async () => {
      addLog('🔒 正在执行需要认证的操作...', 'info')
      
      // 模拟一个需要认证的操作
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      addLog('✅ 安全操作执行成功', 'success')
      return '操作成功'
    }, {
      requireLogin: true,
      validateToken: true,
      loginMessage: '测试：此操作需要登录',
      expiredMessage: '测试：登录已过期'
    })
    
    if (result) {
      addLog(`✅ withAuth 返回结果: ${result}`, 'success')
    }
  } catch (error) {
    addLog(`❌ 安全操作失败: ${error.message}`, 'error')
  }
}

// 测试Token验证
const testValidateAuth = async () => {
  addLog('开始测试Token验证...')
  
  try {
    const isValid = await validateAuth()
    
    if (isValid) {
      addLog('✅ Token验证成功，用户认证有效', 'success')
    } else {
      addLog('❌ Token验证失败，用户已被登出', 'error')
    }
  } catch (error) {
    addLog(`❌ Token验证出错: ${error.message}`, 'error')
  }
}

// 测试退出登录
const testLogout = async () => {
  addLog('开始测试退出登录...')
  
  try {
    const result = await logout(false) // 不显示确认对话框
    
    if (result) {
      addLog('✅ 退出登录成功', 'success')
    } else {
      addLog('❌ 退出登录被取消', 'warning')
    }
  } catch (error) {
    addLog(`❌ 退出登录失败: ${error.message}`, 'error')
  }
}

// 初始化日志
addLog('认证系统测试组件已加载')
</script>

<style scoped>
.auth-test {
  max-width: 800px;
  margin: 20px auto;
}

.test-section {
  margin-bottom: 20px;
}

.test-section h4 {
  margin-bottom: 10px;
  color: #409eff;
}

.test-logs {
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.log-item {
  display: flex;
  margin-bottom: 5px;
  font-family: monospace;
  font-size: 12px;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-item.success .log-message {
  color: #67c23a;
}

.log-item.warning .log-message {
  color: #e6a23c;
}

.log-item.error .log-message {
  color: #f56c6c;
}

.log-item.info .log-message {
  color: #409eff;
}
</style>
